package com.bw.auth.handler;

import com.alibaba.fastjson.JSONObject;
import com.bw.auth.exception.BizException;
import com.bw.common.result.Result;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result bizExceptionHandler(BizException bizException){
        return Result.error(bizException.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> arrayList = new ArrayList<>();
        if (bindingResult.hasErrors()){
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            allErrors.forEach(objectError -> {
                arrayList.add(objectError.getDefaultMessage());
            });
        }
        return Result.error(",", JSONObject.toJSONString(arrayList));
    }

}
